#include "head.h"

int pipe_fd[2];
void func(int num)
{
    write(pipe_fd[1], "1", 1);
}

int main()
{
    // 父进程逻辑
    pipe(pipe_fd);
    if (fork() != 0)
    {
        signal(2, func);
        wait(NULL);
        exit(0);
    }
    setpgid(0, 0);

    // 子进程逻辑
    // 创建子线程
    pool_t pool;
    initPool(&pool, 3);

    // 创建数据库维护用户信息表和文件信息表
    MYSQL *file_db;
    // initMysql(&file_db);

    // 初始化socket通信
    int socket_fd;
    initSocket(&socket_fd);

    // 创建监听，将socket对象加入监听,将管道读端加入监听
    int epfd = epoll_create(1);
    addEpoll(epfd, socket_fd);
    addEpoll(epfd, pipe_fd[0]);

    while (1)
    {
        struct epoll_event list[10];
        int epoll_num = epoll_wait(epfd, list, 10, -1);

        for (int i = 0; i < epoll_num; i++)
        {
            int fd = list[i].data.fd;
            // 如果是管道读端，退出
            if (fd == pipe_fd[0])
            {
                char buf[60] = {0};
                read(pipe_fd[0], buf, sizeof(buf));
                pthread_mutex_lock(&pool.lock);
                pool.exitFlag = 1;
                pthread_cond_broadcast(&pool.cond);
                pthread_mutex_unlock(&pool.lock);

                // 等待子线程全部退出
                for (int j = 0; j < pool.thread_num; j++)
                {
                    pthread_join(pool.thread_ids[j], NULL);
                }
                pthread_exit(NULL);
            }
            // 如果是socket通信，将通信对象加入监听
            if (fd == socket_fd)
            {
                int net_fd = accept(socket_fd, NULL, NULL);
                pthread_mutex_lock(&pool.lock);
                enQueue(&pool.queue, net_fd);
                pthread_cond_signal(&pool.cond);
                pthread_mutex_unlock(&pool.lock);
            }
        }
    }
    return 0;
}
